/**
 * elancom Corporation copy right 2012 - 2015  
 *   
 * $Header: https://192.168.1.224/svn/elancom/product/elancom-platform/trunk/src/main/java/com/elancom/framework/commons/json/parser/deserializer/FieldDeserializer.java 1034 2012-07-02 03:09:12Z lanzhouxue $
 * $Id: FieldDeserializer.java 1034 2012-07-02 03:09:12Z lanzhouxue $
 * $Author: lanzhouxue $
 * $Date: 2012-07-02 11:09:12 +0800 (Mon, 02 Jul 2012) $
 * $Revision: 1034 $
 */
package com.elancom.framework.commons.json.parser.deserializer;

import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.Map;

import com.elancom.framework.commons.json.JSONException;
import com.elancom.framework.commons.json.parser.DefaultJSONParser;
import com.elancom.framework.commons.json.util.FieldInfo;

public abstract class FieldDeserializer {

	protected final FieldInfo fieldInfo;

	protected final Class<?> clazz;

	public FieldDeserializer(Class<?> clazz, FieldInfo fieldInfo) {
		this.clazz = clazz;
		this.fieldInfo = fieldInfo;
	}

	public Method getMethod() {
		return fieldInfo.getMethod();
	}

	public Class<?> getFieldClass() {
		return fieldInfo.getFieldClass();
	}

	public Type getFieldType() {
		return fieldInfo.getFieldType();
	}

	public abstract void parseField(DefaultJSONParser parser, Object object, Type objectType, Map<String, Object> fieldValues);

	public abstract int getFastMatchToken();

	public void setValue(Object object, boolean value) {
		setValue(object, Boolean.valueOf(value));
	}

	public void setValue(Object object, int value) {
		setValue(object, Integer.valueOf(value));
	}

	public void setValue(Object object, long value) {
		setValue(object, Long.valueOf(value));
	}

	public void setValue(Object object, String value) {
		setValue(object, (Object) value);
	}

	public void setValue(Object object, Object value) {
		final Method method = fieldInfo.getMethod();
		if (method != null) {
			try {
				method.invoke(object, value);
			} catch (final Exception e) {
				throw new JSONException("set property error, " + fieldInfo.getName(), e);
			}
		} else if (fieldInfo.getField() != null) {
			try {
				fieldInfo.getField().set(object, value);
			} catch (final Exception e) {
				throw new JSONException("set property error, " + fieldInfo.getName(), e);
			}
		}
	}
}
